﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using LibNoise;

namespace SampleImageGenerator.Rendering
{
	internal class FlatRenderer : IRenderer
	{
		public Image Render(IModule module, IPalette palette, RectangleF sourceRegion, Size size)
		{
			Int32 imageWidth = size.Width;
			Int32 imageHeight = size.Height;
			Bitmap image = new Bitmap(imageWidth, imageHeight);

			Double xScaleFactor = (Double)sourceRegion.Width/(Double)image.Width;
			Double yScaleFactor = (Double)sourceRegion.Height/(Double)image.Height;
			Double xOffset = sourceRegion.Left;
			Double yOffset = sourceRegion.Top;

			Double zd = 0;
			Double maxValue = Double.MinValue;
			Double minValue = Double.MaxValue;
			Double[,] values = new Double[imageWidth, imageHeight]; 
			for (Int32 x = 0; x < imageWidth; x++)
			{
				for (Int32 y = 0; y < imageHeight; y++)
				{
					Double xd = xOffset + (x * xScaleFactor);
					Double yd = yOffset + (y * yScaleFactor);
					Double value = module.GetValue(xd, yd, zd);
					values[x, y] = value;
					if (value < minValue) { minValue = value; }
					if (value > maxValue) { maxValue = value; }
				}
			}

			palette.SetRange(minValue, maxValue); 

			for (Int32 x = 0; x < imageWidth; x++)
			{
				for (Int32 y = 0; y < imageHeight; y++)
				{
					Double value = values[x, y];
					Color colour = palette.GetColour(value);
					image.SetPixel(x, y, colour);
				}
			}

			return image; 
		}
	}
}
